package com.ums.upos.service.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.nexgo.common.ByteUtils;
import com.ums.upos.GlobalDataHolder;
import com.ums.upos.service.AmountReceiver;
import com.ums.upos.service.BeeperBinder;
import com.ums.upos.service.PinKeyCodeEvent;
import com.ums.upos.uapi.R;
import com.ums.upos.uapi.device.beeper.BeepModeConstrants;
import com.ums.upos.uapi.device.beeper.Beeper;
import com.ums.upos.uapi.device.pinpad.PinPadKeyCode;
import com.ums.upos.uapi.engine.LanguageType;
import com.ums.upos.util.LanguageUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.SubscriberExceptionEvent;
import org.greenrobot.eventbus.ThreadMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.NumberFormat;
import java.util.Locale;
import java.util.Random;


/**
 * Created by xiaox on 16/6/27.
 */
public class PinInputDialog extends Dialog implements View.OnClickListener {
    private Toolbar toolbar;
    private TextView mInputPin;
    private TextView mPlsInputPin;
    private TextView mAmount;
    private TextView mAmount_format;
    private Context mContext;
    private boolean mIsFirstInput = true;
    private View mKeyboard;
    private Button mKeyboard_0;
    private Button mKeyboard_1;
    private Button mKeyboard_2;
    private Button mKeyboard_3;
    private Button mKeyboard_4;
    private Button mKeyboard_5;
    private Button mKeyboard_6;
    private Button mKeyboard_7;
    private Button mKeyboard_8;
    private Button mKeyboard_9;
    private OnKeyboadClickListener listener;
    private Button mKeyboard_cancel;
    private Button mKeyboard_clear;
    private Button mKeyboard_confirm;
    private LanguageUtil languageUtil;
    private Beeper beeper;
    private Logger log = LoggerFactory.getLogger("PININPUTDIALOG");

    public PinInputDialog(Context context) {
        super(context);
        this.mContext = context;
    }

    public PinInputDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
    }

    protected PinInputDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        log.error("call PinInputDialog onCreate");
        super.onCreate(savedInstanceState);
        languageUtil = new LanguageUtil(mContext);
        //强制屏幕常亮
        Window win = getWindow();
        win.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //屏蔽菜单键
        win.addFlags(5);
        //屏蔽home键
        win.addFlags(3);
        //屏蔽下拉
        Settings.System.putInt(getContext().getContentResolver(), "status_bar_disabled", 1);
        setContentView(R.layout.dialog_pin_input);
        if(Build.MODEL.equals("N3")){
            beeper = GlobalDataHolder.getInstance().getBeeper();
            if(beeper == null){
                BeeperBinder binder = new BeeperBinder(this.mContext);
                beeper = Beeper.Stub.asInterface(binder);
                GlobalDataHolder.getInstance().setBeeper(beeper);
            }
        }
        initView();
        EventBus.getDefault().register(this);
        setAmount();

//        if(TextUtils.isEmpty(amount)) {
//            log.debug("注册金额广播");
//            IntentFilter filter = new IntentFilter();
//            filter.addAction(AmountReceiver.ACTION);
//            mContext.registerReceiver(mReceiver, filter);
//            isRegistReciver = true;
//        }else{
//            setAmount(amount);
//        }
    }

    private void clear() {
//        if(isRegistReciver) {
//            mContext.unregisterReceiver(mReceiver);
//            isRegistReciver = false;
//        }
        log.error("call PinInputDialog clear");
        GlobalDataHolder.getInstance().setShowAmount(null);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().unregister(this);
    }


    private void initView() {
        log.error("call PinInputDialog initView");
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle(languageUtil.getFirstString(R.string.title_activity_pin_input));
        if(languageUtil.isDiglossia())
            toolbar.setSubtitle(languageUtil.getSecondString(R.string.title_activity_pin_input));
        mKeyboard = findViewById(R.id.keyboard_view);
        mKeyboard.setVisibility(View.GONE);
        mInputPin = (TextView) findViewById(R.id.input_pin);
        mPlsInputPin = (TextView) findViewById(R.id.pls_input_pin);
        mAmount = (TextView) findViewById(R.id.amount);
        mAmount.setText(languageUtil.getString(R.string.amount));
        mAmount_format = (TextView) findViewById(R.id.amount_format);
        mKeyboard_0 = (Button) findViewById(R.id.keyboard_0);
        mKeyboard_0.setOnClickListener(this);
        mKeyboard_1 = (Button) findViewById(R.id.keyboard_1);
        mKeyboard_1.setOnClickListener(this);
        mKeyboard_2 = (Button) findViewById(R.id.keyboard_2);
        mKeyboard_2.setOnClickListener(this);
        mKeyboard_3 = (Button) findViewById(R.id.keyboard_3);
        mKeyboard_3.setOnClickListener(this);
        mKeyboard_4 = (Button) findViewById(R.id.keyboard_4);
        mKeyboard_4.setOnClickListener(this);
        mKeyboard_5 = (Button) findViewById(R.id.keyboard_5);
        mKeyboard_5.setOnClickListener(this);
        mKeyboard_6 = (Button) findViewById(R.id.keyboard_6);
        mKeyboard_6.setOnClickListener(this);
        mKeyboard_7 = (Button) findViewById(R.id.keyboard_7);
        mKeyboard_7.setOnClickListener(this);
        mKeyboard_8 = (Button) findViewById(R.id.keyboard_8);
        mKeyboard_8.setOnClickListener(this);
        mKeyboard_9 = (Button) findViewById(R.id.keyboard_9);
        mKeyboard_9.setOnClickListener(this);
        mKeyboard_cancel = (Button) findViewById(R.id.keyboard_cancel);
        mKeyboard_cancel.setOnClickListener(this);
        mKeyboard_clear = (Button) findViewById(R.id.keyboard_clear);
        mKeyboard_clear.setOnClickListener(this);
        mKeyboard_confirm = (Button) findViewById(R.id.keyboard_confirm);
        mKeyboard_confirm.setOnClickListener(this);
        updateKeyBoard();
    }

    @Override
    public void onClick(View v) {
        int keyCode;
        if (listener != null) {
            switch (v.getId()) {
                case R.id.keyboard_cancel:
                    listener.onSendKey(PinPadKeyCode.KEYCODE_CANCEL);
                    break;
                case R.id.keyboard_clear:
                    listener.onSendKey(PinPadKeyCode.KEYCODE_CLEAR);
                    break;
                case R.id.keyboard_confirm:
                    listener.onSendKey(PinPadKeyCode.KEYCODE_CONFIRM);
                    break;
                default:
                    keyCode = mBind.get(v.getId());
                    listener.onSendKey((byte) (keyCode + 0x30));
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PinKeyCodeEvent event) {
        if (mIsFirstInput) {
            mIsFirstInput = false;
            mInputPin.setText("");
            mInputPin.setTextColor(mContext.getResources().getColor(R.color.pin_mask));
        }
        if(Build.MODEL.equals("N3")){
            try {
                beeper.beep(BeepModeConstrants.NORMAL);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        switch (event.getKeyCode()) {
            case PinPadKeyCode.KEYCODE_STAR:
                mInputPin.append(ByteUtils.asciiByteArray2String(new byte[]{PinPadKeyCode.KEYCODE_STAR}) + " ");
                break;
            case PinPadKeyCode.KEYCODE_CLEAR:
                mIsFirstInput = true;
                mInputPin.setText(R.string.press_enter_when_no_pin);
                mInputPin.setTextColor(mContext.getResources().getColor(R.color.pin_tip));
                break;
            case PinPadKeyCode.KEYCODE_CONFIRM:
            case PinPadKeyCode.KEYCODE_CANCEL:
                log.error("On user press confirm or cancel PinInputDialog");
                dismiss();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(SubscriberExceptionEvent event) {
        log.error("On SubscriberExceptionEvent Evnet");
        clear();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AmountReceiver event) {
        log.error("On AmountReceiver Evnet");
        setAmount();
    }

    public void setInputPinType(boolean isOnlinePin) {
        String msg = String.format(languageUtil.getFirstString(R.string.pls_input_pin),
                isOnlinePin ? languageUtil.getFirstString(R.string.online) : languageUtil.getFirstString(R.string.offline));

        if(languageUtil.isDiglossia()){
            msg = msg + "\n" +
                    String.format(languageUtil.getSecondString(R.string.pls_input_pin),
                            isOnlinePin ? languageUtil.getSecondString(R.string.online) : languageUtil.getSecondString(R.string.offline));
        }
        mPlsInputPin.setText(msg);
        //mPlsInputPin.setText(String.format(getContext().getResources().getString(R.string.pls_input_pin), isOnlinePin ? "联机" : "脱机"));
    }

    private void setAmount() {
        log.error("call setAmount update dialog");
        String amt = GlobalDataHolder.getInstance().getShowAmount();
//        String amt1 = GlobalDataHolder.getInstance().getShowAmount();
        log.error("dialog show Amount:{}", amt);
        if (TextUtils.isEmpty(amt) || "000000000000".equals(amt) || "0.00".equals(amt)) return;
        if (!amt.contains(".")) {
            NumberFormat format = NumberFormat.getInstance();
            format.setMinimumIntegerDigits(1);
            format.setMaximumFractionDigits(2);
            format.setMinimumFractionDigits(2);
            format.setGroupingUsed(false);
            amt = format.format(Long.valueOf(amt) / 100.00);
        }
        mAmount_format.setVisibility(View.VISIBLE);
        mAmount.setVisibility(View.VISIBLE);
        mAmount_format.setText(String.format(getContext().getResources().getString(R.string.amount_format), amt));
    }

    public void showKeyboad() {
        mKeyboard.setVisibility(View.VISIBLE);
    }

    public void setOnKeyboadClickListener(OnKeyboadClickListener listener) {
        this.listener = listener;
    }

//    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            log.debug("收到金额广播");
//            String action = intent.getAction();
//            if (AmountReceiver.ACTION.equals(action)) {
//                Bundle bundle = intent.getExtras();
//                String amt = bundle.getString(AmountReceiver.KEY_AMOUNT);
//                if (!TextUtils.isEmpty(amt)) {
//                    setAmount(amt);
//                }
////                mReceiver.abortBroadcast();
//            }
//        }
//    };

    @Override
    public void dismiss() {
        log.error("call dismiss");
        clear();
        super.dismiss();
    }

    SparseIntArray mBind = new SparseIntArray();

    private void updateKeyBoard() {
        int[] randomKeys = getRandomNum();
        mBind.put(R.id.keyboard_0, randomKeys[0]);
        mBind.put(R.id.keyboard_1, randomKeys[1]);
        mBind.put(R.id.keyboard_2, randomKeys[2]);
        mBind.put(R.id.keyboard_3, randomKeys[3]);
        mBind.put(R.id.keyboard_4, randomKeys[4]);
        mBind.put(R.id.keyboard_5, randomKeys[5]);
        mBind.put(R.id.keyboard_6, randomKeys[6]);
        mBind.put(R.id.keyboard_7, randomKeys[7]);
        mBind.put(R.id.keyboard_8, randomKeys[8]);
        mBind.put(R.id.keyboard_9, randomKeys[9]);
        mKeyboard_0.setText(mBind.get(mKeyboard_0.getId()) + "");
        mKeyboard_1.setText(mBind.get(mKeyboard_1.getId()) + "");
        mKeyboard_2.setText(mBind.get(mKeyboard_2.getId()) + "");
        mKeyboard_3.setText(mBind.get(mKeyboard_3.getId()) + "");
        mKeyboard_4.setText(mBind.get(mKeyboard_4.getId()) + "");
        mKeyboard_5.setText(mBind.get(mKeyboard_5.getId()) + "");
        mKeyboard_6.setText(mBind.get(mKeyboard_6.getId()) + "");
        mKeyboard_7.setText(mBind.get(mKeyboard_7.getId()) + "");
        mKeyboard_8.setText(mBind.get(mKeyboard_8.getId()) + "");
        mKeyboard_9.setText(mBind.get(mKeyboard_9.getId()) + "");
    }

    //生成随机的0-9 10个数字，且值各不相同
    private int[] getRandomNum() {
        Random random = new Random();
        int[] data = new int[10];
        boolean b;
        boolean b2 = false;
        boolean b3 = true;
        int x;
        for (int i = 0; i < 10; i++) {
            b = true;
            while (b) {
                x = random.nextInt(10);
                if (x == 0 && b3) {
                    b3 = false;
                    b = false;
                }
                for (int y : data) {
                    if (x == y) {
                        b2 = false;
                        break;
                    } else {
                        b2 = true;
                    }
                }
                if (b2) {
                    data[i] = x;
                    b = false;
                    break;
                }
            }

        }
        return data;
    }

    public interface OnKeyboadClickListener {
        void onSendKey(byte keyCode);
    }
}
